package com.google.bling.client.widget;

import com.google.bling.client.AddTransactionCallback;
import com.google.bling.client.AddTransactionChannel;
import com.google.bling.client.Util;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.PopupPanel.PositionCallback;

import java.util.List;
import java.util.Map;

public class BlingClient extends Composite {
  private AddExpensePopup popup;

  public BlingClient(final String loggedInUser, final List<String> allUsers, Map<String, Integer> bbf) {
    VerticalPanel vPanel = new VerticalPanel();
    List<String> otherUsers = Util.list();
    otherUsers.addAll(allUsers);
    otherUsers.remove(loggedInUser);

    popup = new AddExpensePopup(loggedInUser, otherUsers);

    final ExpenseTable expenseTable = new ExpenseTable(allUsers, bbf);

    HorizontalPanel buttonPanel = new HorizontalPanel();
    Button addExpenseButton = new Button("Add new expense");

    buttonPanel.add(addExpenseButton);

    addExpenseButton.addClickListener(new ClickListener() {
      public void onClick(Widget sender) {
        popup.setListener(new AddExpensePopup.Listener() {
          public void onExpenseAdded(String description, int amount,
              Map<String, Integer> owedAmounts) {
            expenseTable.addExpense("some date", description, amount,
                owedAmounts);

            List<Integer> amountList = Util.list();
            for (String p : owedAmounts.keySet()) {
              amountList.add(owedAmounts.get(p));
            }
            new AddTransactionChannel().request(6, Util.join(allUsers, ","),
                description, amount, loggedInUser, Util.join(amountList, ","),
                new AddTransactionCallback() {
              public void execute(AddTransactionChannel.Response o) {
                Window.alert("Yeah!");
              }
            });

          }
        });
        popup.setPopupPositionAndShow(new PositionCallback() {
          public void setPosition(int offsetWidth, int offsetHeight) {
            popup.center();
          }
        });
      }
    });

    vPanel.add(expenseTable);
    vPanel.add(buttonPanel);

    initWidget(vPanel);
  }
}
